package com.zhg.shortlink.controller;

import com.zhg.shortlink.constant.CommonConstants;
import com.zhg.shortlink.service.ShortUrlMappingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author 朱洪刚
 * @version 1.0
 * @data 2025/10/20 11:38
 */
@RestController
@RequestMapping("/test")
public class TestController {

    private final ShortUrlMappingService shortUrlMappingService;

    @Autowired
    public TestController(ShortUrlMappingService shortUrlMappingService) {
        this.shortUrlMappingService = shortUrlMappingService;
    }

    @GetMapping("/hello")
    public String hello() {
        return "hello world";
    }
    /**
     * 测试mybatis plus
     */
    @GetMapping("/myps")
    public String myps() {
        long count = shortUrlMappingService.count();
        return "mybatis plus test";
    }

    /**
     * 短链所在库和表位置
     * @param shortCode
     * @return
     */
    @GetMapping("/getDbAndTable/{shortCode}")
    public String getDbAndTable(@PathVariable("shortCode") String shortCode) {
        return "dbName:" + calculateDatabaseIndex(shortCode) + " tableName:" + calculateTableIndex(shortCode);
    }

    /**
     * 计算数据库索引（更新为32个数据库）
     */
    private int calculateDatabaseIndex(String shortCode) {

            return Math.abs(shortCode.hashCode()) % CommonConstants.SHARDING_DATABASE_COUNT;

    }

    /**
     * 计算表索引（更新为256张表）
     */
    private int calculateTableIndex(String shortCode) {

            return Math.abs(shortCode.hashCode()) % CommonConstants.SHARDING_TABLE_COUNT;

    }
}
